package cn.edu.cqupt.mis.ywbd.admin.aspect;

import cn.edu.cqupt.mis.ywbd.admin.annotation.AdminLog;
import cn.edu.cqupt.mis.ywbd.admin.util.HttpContextUtils;
import cn.edu.cqupt.mis.ywbd.admin.util.IpUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author 李国龙
 * @date 2021/4/11
 */
@Aspect
@Component
public class AdminLogAspect {
    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation(cn.edu.cqupt.mis.ywbd.admin.annotation.AdminLog)")
    public void logPoinCut() {
    }

    @AfterReturning(pointcut = "logPoinCut()", returning = "result")
    public void saveSysLog(JoinPoint joinPoint,Map result) {
        System.out.println("切面。。。。。");
        System.out.println(result);
        HttpServletRequest httpServletRequest = HttpContextUtils.getHttpServletRequest();
        String ipAddr = IpUtils.getIpAddr(httpServletRequest);
        System.out.println(ipAddr);
        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        //获取操作
        AdminLog adminLog = method.getAnnotation(AdminLog.class);
        if (adminLog != null) {
            String value = adminLog.value();
            System.out.println(value);
        }

        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取请求的方法名
        String methodName = method.getName();
        System.out.println(className + "." + methodName);

        //请求的参数
        Object[] args = joinPoint.getArgs();

        System.out.println(args[1].toString());
//        //获取用户ip地址
//        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//        sysLog.setIp(IPUtils.getIpAddr(request));
//
//        //调用service保存SysLog实体类到数据库
//        sysLogService.save(sysLog);
    }
}
